package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;//注入老人service
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private IBedService bedService;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //查询老人已存在
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()).one();
        if (elder != null && elder.getStatus() != 5){
            //老人如果已经入住着报错
            throw new BaseException("该老人已入住");
        }

        //修改床位为占用
        bedService.lambdaUpdate().eq(Bed::getId, dto.getCheckInConfigDto().getBedId())
                .set(Bed::getBedStatus, 1).update();
        //如果老人存在则更新，不存在则插入
        if (elder != null){

            //老人存在则更新
            BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
            elder.setStatus(4);
            elderService.updateById(elder);
        }else{
            elder = new Elder();
            BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
            elder.setStatus(4);
            elder.setBedId(dto.getCheckInConfigDto().getBedId());
            String bedNumber = bedService.getById(dto.getCheckInConfigDto().getBedId()).getBedNumber();
            elder.setBedNumber(bedNumber);
            elderService.save(elder);
        }
        //插入入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //获取入住床位
        Bed bed = bedService.getById(dto.getCheckInConfigDto().getBedId());
        if (bed == null){
            throw new BaseException("该床位不存在");
        }
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        //老人亲戚添加到checkIn中
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        String elderFamilys = JSON.toJSONString(elderFamilyDtoList);
        checkIn.setRemark(elderFamilys);
        save(checkIn);

        //插入入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);

        //插入合同信息
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        //合同编号
        String contractNumber = CodeGenerator.generateContractNumber();
        contract.setContractNumber("HT"+contractNumber);
        contractService.save(contract);
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = getById(id);
        if (checkIn == null){
            throw new BaseException("入住信息不存在");
        }
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn, checkInConfigVo);

        //封装老人亲戚
        String remark = checkIn.getRemark();
        if (StringUtils.isNotBlank(remark)){
            // 将JSON字符串转换为ElderFamilyDto对象列表
            List<ElderFamilyVo> elderFamilyDtoList = JSON.parseArray(remark, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyDtoList);
        }

        //查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, id).one();
        if (checkInConfig == null){
            throw new BaseException("入住配置信息不存在");
        }
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //查询老人信息
        Elder elder = elderService.lambdaQuery().eq(Elder::getId, checkIn.getElderId()).one();
        if (elder == null){
            throw new BaseException("老人信息不存在");
        }
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //查询合同信息
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, elder.getId()).one();
        if (contract == null){
            throw new BaseException("合同信息不存在");
        }
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }
}
